package com.guigu.dealservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.common.utils.R;
import com.guigu.dealservice.dto.Equipment;
import com.guigu.dealservice.entity.EquipmentReservation;
import com.guigu.dealservice.entity.Order;
import com.guigu.dealservice.feign.MyEquipmentFeign;
import com.guigu.dealservice.service.EquipmentReservationService;
import com.guigu.dealservice.service.OrderService;
import com.guigu.equipmentservice.service.EquipmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 *  预定表
 * </p>
 *
 * @author janecraft
 * @since 2025-10-17
 */
@RestController
@RequestMapping("/dealservice/equipmentReservation")
public class EquipmentReservationController {
    @Autowired
    private EquipmentReservationService equipmentReservationService;
    @Autowired
    private OrderService orderService;

    @Autowired
    private MyEquipmentFeign myEquipmentFeign;

    //预定设备
    @PostMapping("/equipmentReservationAdd")
    public R equipmentReservationAdd(@RequestBody EquipmentReservation equipmentReservation){
        try {
        equipmentReservation.setReservationStatus(0);
        Integer period = equipmentReservation.getReservationPeriod();
        //过期时间由设备的rentalPeriod和创建时间相加得到
        LocalDateTime createTime = LocalDateTime.now();
        LocalDateTime expireTime =createTime.plusDays(period);
        equipmentReservation.setExpireTime(expireTime);


        //计算尾款金额
            BigDecimal orderAmount = equipmentReservation.getOrderAmount();
            BigDecimal depositAmount = equipmentReservation.getReservationDeposit();
            BigDecimal balanceAmount  = orderAmount.subtract(depositAmount);

        //添加订单表
            Order orderSave = new Order();
            orderSave.setBuyerId(equipmentReservation.getUserId());
            orderSave.setSellerId(equipmentReservation.getSellerId());
            orderSave.setEquipmentId(equipmentReservation.getEquipmentId());
            orderSave.setOrderAmount(equipmentReservation.getOrderAmount());
            orderSave.setDepositAmount(equipmentReservation.getReservationDeposit());
            orderSave.setBalanceAmount(balanceAmount);
            orderSave.setOrderStatus(0);
            orderSave.setCreateTime(LocalDateTime.now());
            orderSave.setUpdateTime(LocalDateTime.now());
            boolean save = equipmentReservationService.save(equipmentReservation);
            boolean orderSave1 = orderService.save(orderSave);
            if (save && orderSave1){
                return R.ok().success(true).code(20000).message("预定成功");
             }else {
                return R.error().success(false).code(20002).message("预定失败");
             }
        } catch (DuplicateKeyException e) {
            return R.error().code(20001).message("你已经预订过了");
        } catch (Exception e) {
            return R.error().code(20002).message("预订失败");
        }
    }

    /**
     * 前台-根据设备id查询设备预定信息状态
     */
    @PostMapping("/selectEquipmentReservationById/{id}")
    public R selectEquipmentReservationById(@PathVariable("id") Long id){
        EquipmentReservation equipmentReservation = equipmentReservationService.selectEquipmentReservationById(id);
        if (equipmentReservation!=null){
            return R.ok().success(true).code(20000).message("已预定").data("equipmentReservation",equipmentReservation);
        }else {
            return R.error().code(20002).message("待预定");
        }
    }


    /**
     * 前台-根据设备id查询设备预定信息状态
     */
    @PostMapping("/selectEquipmentReservationById2/{id}")
    public R selectEquipmentReservationById2(@PathVariable("id") Long id){
        EquipmentReservation equipmentReservation = equipmentReservationService.selectEquipmentReservationById(id);

        //根据预定表的设备id查询订单
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("equipment_id",id);
        Order one = orderService.getOne(wrapper);

        Equipment equipment = myEquipmentFeign.selectEquipmentByIdFeign(id);

        if (one != null){
            equipmentReservation.setOrder(one);
        }

        equipmentReservation.setEquipment(equipment);

        if (equipmentReservation!=null){
            return R.ok().success(true).code(20000).message("已预定").data("equipmentReservation",equipmentReservation);
        }else {
            return R.error().code(20002).message("待预定");
        }
    }
    /**
     * 添加设备预定
     * @param equipmentReservation
     * @return
     */
    @PostMapping("/addEquipmentReservation")
    public R addEquipmentReservation(@RequestBody EquipmentReservation equipmentReservation){
        try {
            equipmentReservation.setReservationStatus(1);
            Integer period = equipmentReservation.getReservationPeriod();
            //过期时间由设备的rentalPeriod和创建时间相加得到
            LocalDateTime createTime = LocalDateTime.now();
            LocalDateTime expireTime =createTime.plusDays(period);
            equipmentReservation.setExpireTime(expireTime);


            //计算尾款金额
            BigDecimal orderAmount = equipmentReservation.getOrderAmount();
            BigDecimal depositAmount = equipmentReservation.getReservationDeposit();
            BigDecimal balanceAmount  = orderAmount.subtract(depositAmount);

            //添加订单表
            Order orderSave = new Order();
            orderSave.setBuyerId(equipmentReservation.getUserId());
            orderSave.setSellerId(equipmentReservation.getSellerId());
            orderSave.setEquipmentId(equipmentReservation.getEquipmentId());
            orderSave.setOrderAmount(equipmentReservation.getOrderAmount());
            orderSave.setDepositAmount(equipmentReservation.getReservationDeposit());
            orderSave.setBalanceAmount(balanceAmount);
            orderSave.setOrderStatus(0);
            orderSave.setCreateTime(LocalDateTime.now());
            orderSave.setUpdateTime(LocalDateTime.now());
            boolean save = equipmentReservationService.save(equipmentReservation);
            boolean orderSave1 = orderService.save(orderSave);
            if (save && orderSave1){
                return R.ok().success(true).code(20000).message("预定成功");
            }else {
                return R.error().success(false).code(20002).message("预定失败");
            }
        } catch (DuplicateKeyException e) {
            return R.error().code(20001).message("你已经预订过了");
        } catch (Exception e) {
            return R.error().code(20002).message("预订失败");
        }
    }
}
